﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DidaCode.Workflow.Logs
{
    public class ExecutionLogger
    {

        private static readonly AsyncLocal<ConcurrentDictionary<string, TypedResult>> _results = new AsyncLocal<ConcurrentDictionary<string, TypedResult>>();

        private static ConcurrentDictionary<string, TypedResult> Results => _results.Value ??= new ConcurrentDictionary<string, TypedResult>();

        private static readonly object _lock = new object();
        public static void LogResult(string nodeName, TypedResult result)
        {
            lock (_lock)
            {
                Results[nodeName] = result;
            }
        }

        public static bool TryGetResult<T>(string nodeName, out T result)
        {
            lock (_lock)
            {
                if (Results.TryGetValue(nodeName, out var typedResult) && typedResult.ResultType == typeof(T))
                {
                    result = typedResult.GetValue<T>();
                    return true;
                }
                result = default;
                return false;
            }
        }

        public static void Clear()
        {
            lock (_lock)
            {
                Results.Clear();
            }
        }
    }


    public class TypedResult
    {
        public Type ResultType { get; }
        public object Value { get; }

        public TypedResult(Type resultType, object value)
        {
            ResultType = resultType;
            Value = value;
        }

        public T GetValue<T>()
        {
            return (T)Value;
        }
    }

}
